package main;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import main.BattleGridTest.ImageLabel;
import spells.Spell;

	public class TestingPanel extends JPanel implements MouseListener, KeyListener{
		ImageLabel [][] labels;
		int ROWS = BattleGridTest.ROWS;
		int COLUMNS = BattleGridTest.COLUMNS;
		public Cell currentCell;
		Player you;
		boolean enemyCaptured;
		public Creature target;
//		public TestingPanel(){
//			//note by ben: GridLayout(x,y) where x = rows, y = columns
//			this.setLayout(new GridLayout(ROWS,COLUMNS));
//			Dimension d = new Dimension (WIDTH,HEIGHT);
//			this.setSize(d);
//			this.setPreferredSize(d);
//			this.setMaximumSize(d);
//			this.setMinimumSize(d);
//			this.addKeyListener(this);
//			Dimension label = new Dimension(50,50);
//			fillOccImages();
//		}
		//w/important constructors
		public TestingPanel(int WIDTH, int HEIGHT){
			 labels = new ImageLabel[ROWS][COLUMNS];
			 this.setLayout(new GridLayout(ROWS,COLUMNS));
				Dimension d = new Dimension (WIDTH,HEIGHT);
				this.setSize(d);
				this.setPreferredSize(d);
				this.setMaximumSize(d);
				this.setMinimumSize(d);
				this.addKeyListener(this);
				Dimension label = new Dimension(50,50);
				fillOccImages();
				ROWS = BattleGridTest.ROWS;
				COLUMNS = BattleGridTest.COLUMNS;
				currentCell=null;
				you = BattleGridTest.you;
				enemyCaptured=false;
				target=null;
		}
		
		//assumes all occupants have images assigned - fills in labels with appropriate images and combines 
		//terrain images with creature images
		public void fillOccImages(){
			//row (i)
			for (int i=ROWS-1;i>=0;i--){
				//column (j) 
				for (int j=0;j<COLUMNS;j++){
					//System.out.println("i/row: " + i + ", j/column: " + j);
					//different things if there is a creature image or not in the current cell
					String terrImgString;
					Grid temp=BattleGridTest.currentGrid;
					if (temp.cellGrid[j][i].hasOccupant()){
						BufferedImage cellImage = new BufferedImage(50,50,BufferedImage.TYPE_INT_ARGB);
						Graphics2D stuff = (Graphics2D)cellImage.getGraphics();
						MediaTracker track = new MediaTracker(this);
						String occImgString = BattleGridTest.currentGrid.cellGrid[j][i].getOccImage();
						if (BattleGridTest.currentGrid.tile != null)
							 terrImgString = BattleGridTest.currentGrid.tile;
						else
							 terrImgString = BattleGridTest.currentGrid.cellGrid[j][i].getTerrImage();
						Image occImage = Toolkit.getDefaultToolkit().getImage(occImgString);
						track.addImage(occImage, 1);
						Image terrImage = Toolkit.getDefaultToolkit().getImage(terrImgString);
						track.addImage(terrImage, 0);


						try {
							track.waitForAll();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						stuff.drawImage(terrImage,0,0,null);
						stuff.drawImage(occImage,0,0,null);
						if (labels[i][j] == null)
							labels[i][j] = new ImageLabel(i+","+j, new ImageIcon (cellImage), j, i);
						else
							labels[i][j].setIcon(new ImageIcon (cellImage));
					}
					else {
						BufferedImage cellImage = new BufferedImage(50,50,BufferedImage.TYPE_INT_ARGB);
						Graphics2D stuff = (Graphics2D)cellImage.getGraphics();
						MediaTracker track = new MediaTracker(this);
						if (BattleGridTest.currentGrid.tile != null)
							 terrImgString = BattleGridTest.currentGrid.tile;
						else
							 terrImgString = BattleGridTest.currentGrid.cellGrid[j][i].getTerrImage();
						Image terrImage = Toolkit.getDefaultToolkit().getImage(terrImgString);
						track.addImage(terrImage, 0);
						try {
							track.waitForAll();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						stuff.drawImage(terrImage,0,0,null);
						//if label never initialized create new imagelabel, else simply replace imagelabel image with terrain
						if (labels[i][j] == null)
							labels[i][j] = new ImageLabel(i+","+j, new ImageIcon (cellImage), j,i);
						else {
							labels[i][j].setIcon(new ImageIcon (cellImage));
							labels[i][j].setCoords(j, i);
						}
					}

				}
			}
			setLabelsToPanel();
		}
		
		//places imagelabels from array into JPanel and adds mouselistener - ensures only one mouselistener is added to avoid
		//problems
		public void setLabelsToPanel(){
			this.removeAll();
			for (int i=ROWS-1;i>=0;i--){
				//column
				for (int j=0;j<COLUMNS;j++){
					add(labels[i][j]);
					if (labels[i][j].getMouseListeners().length < 1)
					labels[i][j].addMouseListener(this);
				}
			}
		}
	
		public void mouseClicked(MouseEvent e) {
			ImageLabel i = (ImageLabel)e.getSource();
			Cell tempCell=BattleGridTest.currentGrid.cellGrid[i.x][i.y];;
			if(tempCell.getOccupant()!=null){
				currentCell=tempCell;
				target=(Creature)currentCell.getOccupant();
				BattleGridTest.console.eName.setText(target.name);
				BattleGridTest.console.eHealth.setText(target.curHealth+"/"+target.maxHealth);
				BattleGridTest.console.eMana.setText(target.curMana+"/"+target.maxMana);
			//	enemyCaptured=true;
			}//end if
			else{
				target=null;
				BattleGridTest.console.eName.setText("");
				BattleGridTest.console.eHealth.setText("");
				BattleGridTest.console.eMana.setText("");
			}//end else
			
			System.out.println("this is the pos of the label u clickxted: x:" + i.x + " y:" + i.y);
		}
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub
		//	BattleGridTest.console.requestFocusInWindow();
			
		}
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		public void keyPressed(KeyEvent e) 
		{
			double timeUntilNextAct = BattleGridTest.timeUntilNextAct;
			double eTimeUntilNextAct = BattleGridTest.eTimeUntilNextAct;
			int code = e.getKeyCode();
			System.out.println(code);
			if (code == KeyEvent.VK_UP || code == KeyEvent.VK_DOWN || code == KeyEvent.VK_LEFT || code == KeyEvent.VK_RIGHT || code == KeyEvent.VK_A || code==KeyEvent.VK_1 || code==KeyEvent.VK_2 || code==KeyEvent.VK_3 || code==KeyEvent.VK_4){
				if (timeUntilNextAct <= 0){
					if (code == KeyEvent.VK_UP)
					{
						BattleGridTest.currentGrid.getPC().moveUp();
						fillOccImages();
						timeUntilNextAct += 0.5;
					}//en else if
					else if (code == KeyEvent.VK_DOWN)
					{
						BattleGridTest.currentGrid.getPC().moveDown();
						fillOccImages();
						timeUntilNextAct += 0.5;
					}//end else if
					else if (code == KeyEvent.VK_LEFT)
					{
						BattleGridTest.currentGrid.getPC().moveLeft();
						fillOccImages();
						timeUntilNextAct += 0.5;
					}//end else if
					else if (code == KeyEvent.VK_RIGHT)
					{
						BattleGridTest.currentGrid.getPC().moveRight();
						fillOccImages();
						timeUntilNextAct += 0.5;
					}//end else if
					else if(code==KeyEvent.VK_1){
						//System.out.println("REACHED;");
						Spell temp=you.findSpell("Fireball");
						temp.setTarget(target);
						String cast = temp.applySpell(BattleGridTest.currentGrid);
						temp.setTarget(null);
						System.out.println(cast);
						BattleGridTest.console.textArea.append(target.name+ " Health is now: " + target.curHealth + "/" + target.maxHealth + "\n");
						//System.out.println(currentCell.getOccupant().name+ " Health is now: " + ((Creature)(currentCell.getOccupant())).curHealth + "/" + ((Creature)(currentCell.getOccupant())).maxHealth);
						BattleGridTest.console.eName.setText(target.name);
						BattleGridTest.console.eHealth.setText(target.curHealth+"/"+target.maxHealth);
						BattleGridTest.console.eMana.setText(target.curMana+"/"+target.maxMana);
						timeUntilNextAct = timeUntilNextAct + temp.getCastTime();
					/*	boolean flag=((Creature) currentCell.getOccupant()).checkDeath();
						if(flag){
							BattleGridTest.console.textArea.append("\n"+currentCell.getOccupant().name+" has died");
						//	System.out.println(currentCell.getOccupant().name+" has died");
							you.gainXP(((Enemy)(currentCell.getOccupant())).experience,((Enemy)(currentCell.getOccupant())).level );

							BattleGridTest.currentGrid.creatures.remove(currentCell.getOccupant());
							currentCell.removeOccupant();
						}*/
					}
				
				else if(code==KeyEvent.VK_2){
					Spell temp=you.findSpell("Heal");
					String cast = temp.applySpell(BattleGridTest.currentGrid);
					System.out.println(cast);
					BattleGridTest.console.textArea.append(you.name+"'s health is now "+you.curHealth+"/"+you.maxHealth + "\n");
					//System.out.println(you.name+"'s health is now "+you.curHealth+"/"+you.maxHealth);
					timeUntilNextAct = timeUntilNextAct + temp.getCastTime();
				}//end else if
				else if(code==KeyEvent.VK_3){
					Spell temp=you.findSpell("Ignite");
					temp.setTarget((Creature) currentCell.getOccupant());
					String cast = temp.applySpell(BattleGridTest.currentGrid);
					temp.setTarget(null);
					BattleGridTest.console.textArea.append(cast+"\n");
					//BattleGridTest.console.textArea.append("\n"+currentCell.getOccupant().name+" Health is now: " + ((Creature)(currentCell.getOccupant())).curHealth + "/" + ((Creature)(currentCell.getOccupant())).maxHealth);
					Creature temp2=(Creature)currentCell.getOccupant();
					BattleGridTest.console.eName.setText(temp2.name);
					BattleGridTest.console.eHealth.setText(temp2.curHealth+"/"+temp2.maxHealth);
					BattleGridTest.console.eMana.setText(temp2.curMana+"/"+temp2.maxMana);
					//	System.out.println(currentCell.getOccupant().name+" Health is now: " + ((Creature)(currentCell.getOccupant())).curHealth + "/" + ((Creature)(currentCell.getOccupant())).maxHealth);
					timeUntilNextAct = timeUntilNextAct + temp.getCastTime();
					/*boolean flag=((Creature) currentCell.getOccupant()).checkDeath();
					if(flag){
						BattleGridTest.console.textArea.append("\n"+currentCell.getOccupant().name+" has died");
						//System.out.println(currentCell.getOccupant().name+" has died");
						you.gainXP(((Enemy)(currentCell.getOccupant())).experience, ((Enemy)(currentCell.getOccupant())).level);
						BattleGridTest.currentGrid.creatures.remove(currentCell.getOccupant());
						currentCell.removeOccupant();
					}*/
				}//end else if
				else if(code==KeyEvent.VK_4){
					Spell temp=you.findSpell("Replenish");
					temp.setTarget((Creature) currentCell.getOccupant());
					String cast = temp.applySpell(BattleGridTest.currentGrid);
					temp.setTarget(null);
					System.out.println(cast);
					BattleGridTest.console.textArea.append(currentCell.getOccupant().name+" Health is now: " + ((Creature)(currentCell.getOccupant())).curHealth + "/" + ((Creature)(currentCell.getOccupant())).maxHealth + "\n");
					Creature temp2=(Creature)currentCell.getOccupant();
					BattleGridTest.console.eName.setText(temp2.name);
					BattleGridTest.console.eHealth.setText(temp2.curHealth+"/"+temp2.maxHealth);
					BattleGridTest.console.eMana.setText(temp2.curMana+"/"+temp2.maxMana);
					//System.out.println(currentCell.getOccupant().name+" Health is now: " + ((Creature)(currentCell.getOccupant())).curHealth + "/" + ((Creature)(currentCell.getOccupant())).maxHealth);
					timeUntilNextAct = timeUntilNextAct + temp.getCastTime();
					/*boolean flag=((Creature) currentCell.getOccupant()).checkDeath();
					if(flag){
						BattleGridTest.console.textArea.append("\n"+currentCell.getOccupant().name+" has died");
						//System.out.println(currentCell.getOccupant().name+" has died");
						you.gainXP(((Enemy)(currentCell.getOccupant())).experience, ((Enemy)(currentCell.getOccupant())).level);
						BattleGridTest.currentGrid.creatures.remove(currentCell.getOccupant());
						currentCell.removeOccupant();
					}*/
				}//end else if
				else if (code == KeyEvent.VK_A){
					Enemy temp=(Enemy)currentCell.getOccupant();
					if (!BattleGridTest.currentGrid.occupants.contains(temp)){
						BattleGridTest.console.textArea.append("No Occupants!");
						//System.out.println("No occupants!");
					}
					else if (BattleGridTest.currentGrid.getDToEnemy(temp) <= 1){
						
						int damage = Player.attackDamage(you.strength,you.weapon1.damage,you.level,temp.armor);
						BattleGridTest.console.textArea.append("You attack enemy for " + damage + " damage.\n");
					//	System.out.println("You attack enemy for " + damage + " damage.");
						temp.takeDamage(damage);
						BattleGridTest.console.textArea.append("Enemy Health is now: " + temp.curHealth + "/" + ((Creature)(currentCell.getOccupant())).maxHealth  + "\n");
						Creature temp2=(Creature)currentCell.getOccupant();
						BattleGridTest.console.eName.setText(temp2.name);
						BattleGridTest.console.eHealth.setText(temp2.curHealth+"/"+temp2.maxHealth);
						BattleGridTest.console.eMana.setText(temp2.curMana+"/"+temp2.maxMana);
						//	System.out.println("Enemy Health is now: " + temp.curHealth + "/" + ((Creature)(currentCell.getOccupant())).maxHealth);
						timeUntilNextAct = timeUntilNextAct + you.weapon1.attackSpeed;
						/*boolean flag=temp.checkDeath();
						if(flag){
							BattleGridTest.console.textArea.append("\n"+"Enemy has died");
						//	System.out.println("Enemy has died");
							you.gainXP(temp.experience, temp.level);
							BattleGridTest.currentGrid.creatures.remove(temp);
							//wolf=null; unused?
						}//end if*/
						timeUntilNextAct += 0.5;
					}//end if
					
				}//end else if
					BattleGridTest.timeUntilNextAct=timeUntilNextAct;
		//		currentPanel.fillOccImages();

			}//end if
				
		}//end if
			}//end if key is valid		

		public void keyReleased(KeyEvent e) {
		}

		public void keyTyped(KeyEvent e) {
			// TODO Auto-generated method stub

		}
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub

		}
		

		
		/* 
		 * Special labels with icons
		 */
		public class ImageLabel extends JLabel{
			int x;
			int y;
			public ImageLabel(String s, ImageIcon image, int x, int y){
				Dimension label = new Dimension(50,50);
				setMinimumSize(label);
				setMaximumSize(label);
				setSize(label);
				this.x = x;
				this.y = y;
				//setText(s);
				this.setIcon(image);
				//this.setText(labelT);
			}
			public void setCoords(int x, int y){
				this.x = x;
				this.y = y;
			}
		}
	}
